package org.example.projecttwo.utils;

import org.example.projecttwo.service.Icommon.IRedisService;
import org.example.projecttwo.service.Imessage.IMessageRedisService;
import org.example.projecttwo.service.Imessage.IMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Component
public class MessageExpiryHandle {

    private static final Logger logger = LoggerFactory.getLogger(MessageExpiryHandle.class);
    private static final String EXPIRY_ZSET_KEY = "message:expirations"; // 过期的消息ID集合

    @Autowired
    private IMessageService messageService;

    @Autowired
    private IMessageRedisService messageRedisService;

    @Autowired
    private IRedisService redisService;

    /**
     * 定期检查并处理过期消息
     * 每分钟执行一次
     */
    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    public void handleExpiredMessages() {
        try {
            // 获取当前时间
            long currentTime = System.currentTimeMillis();
            logger.info("开始检查过期消息，当前时间+{}", new java.util.Date(currentTime));

            //1.从Redis中获取所有过期消息的ID
            Set<Object> expiredMessages = redisService.zRangeByScore(EXPIRY_ZSET_KEY, 0, currentTime);

            if (expiredMessages != null && !expiredMessages.isEmpty()) {
                logger.info("找到{}个过期消息", expiredMessages.size());

                List<Long> expiredMessageIds = new ArrayList<>();
                for (Object obj : expiredMessages) {
                    if (obj instanceof Long) {
                        expiredMessageIds.add((Long) obj);
                    } else if (obj instanceof Integer) {
                        expiredMessageIds.add(((Integer) obj).longValue());
                    }
                }

                if (!expiredMessageIds.isEmpty()) {
                    //2.批量更新消息状态为已过期
                    messageService.batchUpdateStatus(expiredMessageIds, 1);
                    logger.info("批量更新{}条消息状态为已过期", expiredMessageIds.size());

                    //3.从Redis中移除这些消息的过期时间
                    messageRedisService.batchRemoveMessageExpiry(expiredMessageIds);
                }
            } else {
                logger.info("没有找到过期消息");
            }

        } catch (Exception e) {
            logger.error("处理过期消息出错：", e);
        }
    }
}